package me.zhengjie.utils;

import me.zhengjie.domain.vo.ImageContentModel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author cui
 */
public class portraitUtil {

    public  static  void main(String[] args) throws IOException {
        //证书模板路径
//        String cert_templ = portraitUtil.class.getClass().getResource("C:\\Users\\Lenovo\\Desktop\\图片\\BURGER.png").getFile();
        //获取背景路径
        File fiels = new File("D:\\360Downloads\\warm_symmetric_gradient_image.jpg");
        //图片输出路径
        File outfiels = new File("D:\\360Downloads\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".png");
        //模型
        ImageContentModel model = new ImageContentModel("XXXXXXXXX学会", "团体会员",
                "XXXXXXXXX有限公司", "十九",
                new QRCodeGeneration().GenerateQrCode("https://www.baidu.com", 250, 0), "BaiDu198419001", new Date());
        BufferedImage images = ImageGen(fiels, model);
        ImageIO.write(images, "png", outfiels);
    }
    public static BufferedImage ImageGen(File bgfiels,ImageContentModel model) throws IOException {
        //获取背景图片
        BufferedImage bgImg = ImageIO.read(bgfiels);
        //获取背景的宽高
        Integer width=bgImg.getWidth();
        Integer height=bgImg.getHeight();
        //创建Graphics2D对象
        Graphics2D g = bgImg.createGraphics();
        //写入文字
        //设置对线段的锯齿状边缘处理
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        //写入标题
        g.setColor(Color.BLACK);
        g.setFont(new Font("宋体",Font.BOLD,50));
        //标题居中
        FontMetrics title = g.getFontMetrics(new Font("宋体",Font.BOLD,50));
        int titleWidth = title.stringWidth(model.getTitle());// 文字宽度
        int titleCenterX = width / 2;// 计算出中心点 x 位置
        g.drawString(model.getTitle(), titleCenterX - titleWidth / 2, 250);

        //写入证书类型
        g.setColor(Color.ORANGE);
        g.setFont(new Font("宋体",Font.BOLD,150));
        //证书类型居中
        FontMetrics certType = g.getFontMetrics(new Font("宋体",Font.BOLD,150));
        int certTypeWidth = certType.stringWidth(model.getMemberCertType()+"证书");// 文字宽度
        int certTypecenterX = width / 2;// 计算出中心点 x 位置
        g.drawString(model.getMemberCertType()+"证书", certTypecenterX - certTypeWidth / 2, 450);
        //写入单位
        g.setColor(Color.BLACK);
        g.setFont(new Font("宋体",Font.BOLD,50));
        g.drawString(model.getMemberCompany()+":",230,600);
        //写入内容
        g.setColor(Color.BLACK);
        g.setFont(new Font("宋体",Font.LAYOUT_LEFT_TO_RIGHT,55));
        drawStringWithMultiLine(g,new Font("宋体",Font.LAYOUT_LEFT_TO_RIGHT,55),
                "    经"+model.getTitle()+"会员管理部及秘书处研究共同决定，"+model.getMemberCompany()+
                        "资质通过审核，即日起成为"+model.getTitle()+
                        "第"+model.getMemberContent()+"届"+model.getMemberCertType(),
                1400,230,700,0);
        //写入二维码
        g.drawImage(model.getMemberQR(),1300,800,250,250, null);
        //写入编号
        g.setColor(Color.BLACK);
        g.setFont(new Font("宋体",Font.LAYOUT_LEFT_TO_RIGHT,40));
        g.drawString("证书编号："+model.getMemberNo(),280,1100);
        //写入日期
        g.setColor(Color.BLACK);
        g.setFont(new Font("宋体",Font.LAYOUT_LEFT_TO_RIGHT,50));
        g.drawString(new SimpleDateFormat("yyyy年MM月dd日").format(model.getMemberCertDate()),1300,1100);
        g.dispose();
        return bgImg;
    }

    /**
     * Graphic2D文本绘制换行，多行绘制
     *
     * @param graphics2D  Graphics2D画笔实例
     * @param text        需要绘制的文本内容
     * @param maxWidth    一行的总宽度（像素）
     * @param startX      X坐标起始点（像素）
     * @param startY      Y坐标起始点（像素）
     * @param heightSpace 每行间距（像素）
     */
    public static void drawStringWithMultiLine(Graphics2D graphics2D,Font font, String text, int maxWidth, int startX, int startY, int heightSpace) {

        FontMetrics fontMetrics = graphics2D.getFontMetrics(font);
        int textLength = text.length();
        int totalWidth = fontMetrics.stringWidth(text); //一行的总长度，用于判断是否超出了范围
        int textHeight = fontMetrics.getHeight(); //计算一行的高度

        if (totalWidth > maxWidth) {
            // 总长度超过了整个长度限制
            int alreadyWriteLine = 0; //已经写了多少行
            int nowWidth = 0; //目前一行写的长度
            for (int i = 0; i < textLength; i++) {
                int oneWordWidth = fontMetrics.charWidth(text.charAt(i)); //获取单个字符的长度
                int tempWidth = oneWordWidth + nowWidth; //判断目前的一行加上这个字符的长度是否超出了总长度
                if (tempWidth > maxWidth) {
                    // 如果超出了一行的总长度，则要换成下一行
                    nowWidth = 0;
                    alreadyWriteLine++;
                    int writeY = startY + alreadyWriteLine * (textHeight + heightSpace);
                    graphics2D.drawString(text.charAt(i) + "", startX + nowWidth, writeY);
                    nowWidth = oneWordWidth;
                } else {
                    // 当前行长度足够，可以直接画
                    int writeY = startY + alreadyWriteLine * (textHeight + heightSpace);
                    graphics2D.drawString(text.charAt(i) + "", startX + nowWidth, writeY);
                    nowWidth = tempWidth;
                }
            }
        } else {
            // 没有超过限制，直接画
            graphics2D.drawString(text, startX, startY);
        }
    }
}
